<style>
    /* 输入框弹窗样式 */
    .TK-CKSCJ-MY-input-container {
        padding: 20px;
    }

    /* 列表容器样式 */
    .TK-CKSCJ-MY-items {
        padding: 15px;
        background: #f9f9f9;
        border-radius: 8px;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 15px;
    }

    /* 滚动条样式 */
    .TK-CKSCJ-MY-items::-webkit-scrollbar {
        width: 6px;
    }

    .TK-CKSCJ-MY-items::-webkit-scrollbar-thumb {
        background: #1E9FFF;
        border-radius: 3px;
    }

    .TK-CKSCJ-MY-items::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    /* 列表项样式 */
    .TK-CKSCJ-MY-item {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        overflow: hidden;
        height: 100%;
        transition: transform 0.3s ease;
    }

    .TK-CKSCJ-MY-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    }

    /* 修改内容布局为垂直方向 */
    .TK-CKSCJ-MY-content {
        display: flex;
        flex-direction: column;
        padding: 12px;
        cursor: pointer;
    }

    /* 缩略图容器 */
    .TK-CKSCJ-MY-thumb-container {
        width: 100%;
        margin-bottom: 10px;
        position: relative;
        padding-top: 56.25%; /* 16:9 比例 */
    }

    /* 缩略图样式 */
    .TK-CKSCJ-MY-thumb {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
    }

    /* 信息区域样式 */
    .TK-CKSCJ-MY-info {
        flex: 1;
        min-width: 0;
    }

    .TK-CKSCJ-MY-title {
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        line-height: 1.4;
    }

    .TK-CKSCJ-MY-meta {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .TK-CKSCJ-MY-line {
        font-size: 12px;
        color: #666;
        background: #f0f7ff;
        padding: 2px 8px;
        border-radius: 4px;
    }

    .TK-CKSCJ-MY-time {
        font-size: 12px;
        color: #999;
    }

    /* 搜索框容器 */
    .TK-CKSCJ-MY-search-container {
        padding: 15px;
        background: #fff;
        border-bottom: 1px solid #eee;
        position: sticky;
        top: 0;
        z-index: 1;
    }

    .TK-CKSCJ-MY-search-input {
        height: 36px;
        padding: 0 15px;
        border: 1px solid #e6e6e6;
        border-radius: 18px;
        font-size: 14px;
        transition: all 0.3s;
    }

    .TK-CKSCJ-MY-search-input:focus {
        border-color: #1E9FFF;
        box-shadow: 0 0 0 2px rgba(30,159,255,0.1);
        outline: none;
    }

    /* 搜索结果计数 */
    .TK-CKSCJ-MY-search-count {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
        text-align: right;
    }

    /* 导入按钮样式 */
    .TK-CKSCJ-MY-import-btn {
        position: absolute;
        right: 15px;
        top: 50%;
        transform: translateY(-50%);
        padding: 6px 15px;
        background: #1E9FFF;
        color: #fff;
        border: none;
        border-radius: 18px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s;
    }

    .TK-CKSCJ-MY-import-btn:hover {
        background: #0d8aff;
    }

    /* 导入进度样式 */
    .TK-CKSCJ-MY-import-progress {
        margin-top: 10px;
        font-size: 12px;
        color: #666;
    }

    /* 移动端适配 */
    @media screen and (max-width: 768px) {
        .TK-CKSCJ-MY-items {
            grid-template-columns: repeat(2, 1fr);  /* 手机端固定两列 */
            gap: 10px;
            padding: 10px;
        }

        .TK-CKSCJ-MY-content {
            padding: 8px;
        }

        .TK-CKSCJ-MY-thumb-container {
            margin-bottom: 8px;
        }

        .TK-CKSCJ-MY-title {
            font-size: 12px;
            margin-bottom: 6px;
        }

        .TK-CKSCJ-MY-meta {
            gap: 5px;
        }

        .TK-CKSCJ-MY-line,
        .TK-CKSCJ-MY-time {
            font-size: 10px;
        }

        .layui-layer.TK-CKSCJ-MY-layer {
            width: 100% !important;
            height: 100% !important;
            top: 0 !important;
            left: 0 !important;
            margin: 0 !important;
            border-radius: 0 !important;
        }

        .TK-CKSCJ-MY-search-container {
            padding: 10px;
        }

        .TK-CKSCJ-MY-search-input {
            height: 32px;
            font-size: 13px;
        }

        .TK-CKSCJ-MY-import-btn {
            position: static;
            transform: none;
            margin-top: 10px;
            width: 100%;
            padding: 8px;
        }

        .TK-CKSCJ-MY-search-container {
            display: flex;
            flex-direction: column;
        }
    }

    /* 大屏幕适配 */
    @media screen and (min-width: 1200px) {
        .TK-CKSCJ-MY-items {
            grid-template-columns: repeat(3, 1fr);  /* 大屏幕显示三列 */
        }
    }
</style>

<script>
    async function viewCollection() {
        // 1. 弹出输入框
        layer.prompt({
            title: '请输入收藏集TKID',
            formType: 0,
            area: ['300px', '150px']
        }, async function(tkid, index) {
            // 显示加载提示
            const loadingIndex = layer.msg('正在加载数据...', {
                icon: 16,
                shade: 0.3,
                time: 0
            });

            try {
                // 2. 获取收藏列表
                const response = await axios.get(`${window.location.origin}/api/not_login/collection/item/list/`, {
                    params: { tkid }
                });

                if (response.data.status !== 0) {
                    layer.close(loadingIndex);
                    layer.msg('获取失败：' + response.data.message, {icon: 2});
                    return;
                }

                // 3. 提取所有不同的线路
                const lines = [...new Set(response.data.data.map(item => item.line))];
                
                // 4. 获取每个线路的域名
                const lineUrls = await Promise.all(lines.map(async line => {
                    const lineResponse = await axios.get(ApiDomain + 'api/scraper/hei_liao/settings/get_line_url/', {
                        params: { line_name: `line${line}` }
                    });
                    // {
                    //     "url": "https://argue.xlngffea.cc",
                    //     "img_domain": "https://pic.uxyimg.cn"
                    // }
                    
                    return {
                        line,
                        data: lineResponse.data
                    };
                }));

                // 5. 处理数据，添加完整的URL
                const processedData = response.data.data.map(item => {
                    
                    let lineDomain = '';
                    let lineImgDomain = '';
                    lineUrls.forEach(l => {
                        if (l.line == item.line) {
                            lineDomain = l.data.url;
                            lineImgDomain = l.data.img_domain;
                        }
                    });
                    return {
                        ...item,
                        fullUrl: lineDomain + item.url,
                        fullCover: lineImgDomain + item.cover
                    };
                });
                
                // 关闭加载和输入框
                layer.close(loadingIndex);
                layer.close(index);

                // 6. 显示数据列表
                layer.open({
                    type: 1,
                    title: '收藏集内容',
                    area: ['800px', '80%'],
                    skin: 'TK-CKSCJ-MY-layer',
                    content: `
                        <div class="TK-CKSCJ-MY-search-container">
                            <input type="text" 
                                   class="TK-CKSCJ-MY-search-input" 
                                   placeholder="搜索标题..."
                                   oninput="handleSearch(this.value)">
                            <button class="TK-CKSCJ-MY-import-btn" onclick="importToLocal()">
                                导入到收藏
                            </button>
                            <div class="TK-CKSCJ-MY-search-count"></div>
                        </div>
                        <div class="TK-CKSCJ-MY-items">
                            ${processedData.map(item => `
                                <div class="TK-CKSCJ-MY-item" data-title="${(item.title || '').toString().toLowerCase()}">
                                    <div class="TK-CKSCJ-MY-content" onclick="viewDetail('${item.fullUrl}', 'line${item.line}')">
                                        <div class="TK-CKSCJ-MY-thumb-container">
                                            <img class="TK-CKSCJ-MY-thumb" 
                                                 src="${item.fullCover}"
                                                 data-src="${item.fullCover}"
                                                 data-line="${item.line}"
                                                 alt="${item.title}">
                                        </div>
                                        <div class="TK-CKSCJ-MY-info">
                                            <div class="TK-CKSCJ-MY-title">${item.title}</div>
                                            <div class="TK-CKSCJ-MY-meta">
                                                <span class="TK-CKSCJ-MY-line">线路${item.line}</span>
                                                <span class="TK-CKSCJ-MY-time">${item.created_at}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    `,
                    success: function(layero) {
                        // 保存数据到全局变量，供搜索使用
                        window.currentCollectionData = {
                            items: layero.find('.TK-CKSCJ-MY-item'),
                            total: processedData.length
                        };

                        // 处理线路2的图片
                        layero.find('.TK-CKSCJ-MY-thumb').each(function() {
                            const $img = $(this);
                            const line = $img.data('line');
                            const src = $img.data('src');
                            
                            if (line === 2) {
                                loadBackgroundImage(src, this);
                            } else {
                                $img.attr('src', src);
                            }
                        });
                    }
                });

            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('获取失败：' + (error.response?.data?.message || error.message), {
                    icon: 2,
                    time: 2000
                });
            }
        });
    }

    // 搜索处理函数
    function handleSearch(keyword) {
        if (!window.currentCollectionData) return;
        
        const searchText = keyword.toLowerCase().trim();
        let matchCount = 0;

        window.currentCollectionData.items.each(function() {
            const title = String($(this).data('title') || '');  // 确保转换为字符串
            const isMatch = title.includes(searchText);
            
            if (isMatch) {
                $(this).show();
                matchCount++;
            } else {
                $(this).hide();
            }
        });

        // 更新搜索结果计数
        const countText = searchText 
            ? `找到 ${matchCount} 个结果`
            : `共 ${window.currentCollectionData.total} 个项目`;
            
        $('.TK-CKSCJ-MY-search-count').text(countText);
    }

    // 导入到本地收藏
    async function importToLocal() {
        // 确认导入
        layer.confirm('确定要将当前显示的内容导入到本地收藏吗？', {
            btn: ['确定','取消'],
            title: '导入确认'
        }, async function(index){
            layer.close(index);
            
            // 获取当前显示的项目
            const visibleItems = $('.TK-CKSCJ-MY-item:visible');
            if (visibleItems.length === 0) {
                layer.msg('没有可导入的内容', {icon: 2});
                return;
            }

            // 显示加载提示
            const loadingIndex = layer.msg('正在导入...', {
                icon: 16,
                shade: 0.3,
                time: 0
            });

            try {
                // 获取现有记录
                let localRecords = JSON.parse(localStorage.getItem(localStorageKey) || '[]');
                // 修改为使用完整URL进行比对
                const existingUrls = new Set(localRecords.map(record => {
                    const line = record.line.replace('line', '');
                    return `line${line}_${record.url}`;
                }));

                // 收集新记录
                const newRecords = [];
                let skippedCount = 0;

                // 处理每个项目
                visibleItems.each(function() {
                    const $item = $(this);
                    const $content = $item.find('.TK-CKSCJ-MY-content');
                    const fullUrl = $content.attr('onclick').match(/'([^']+)'/)[1];
                    const line = $item.find('.TK-CKSCJ-MY-line').text().replace('线路', '');
                    
                    // 检查是否已存在
                    if (existingUrls.has(`line${line}_${fullUrl}`)) {
                        skippedCount++;
                        return;
                    }

                    // 获取图片完整URL
                    const fullCover = $item.find('.TK-CKSCJ-MY-thumb').attr('data-src');

                    // 创建新记录
                    const newRecord = {
                        title: $item.find('.TK-CKSCJ-MY-title').text(),
                        url: fullUrl,  // 使用完整URL
                        cover: fullCover,  // 使用完整的图片URL
                        timestamp: new Date().toISOString(),
                        line: `line${line}`  // 添加 "line" 前缀
                    };

                    newRecords.push(newRecord);
                });

                // 添加新记录
                if (newRecords.length > 0) {
                    localRecords = [...localRecords, ...newRecords];
                    localStorage.setItem(localStorageKey, JSON.stringify(localRecords));
                }

                // 关闭加载提示
                layer.close(loadingIndex);

                // 显示结果
                const successMsg = newRecords.length > 0 
                    ? `成功导入 ${newRecords.length} 条记录` 
                    : '没有新的记录需要导入';
                const skipMsg = skippedCount > 0 
                    ? `，${skippedCount} 条记录已存在被跳过` 
                    : '';
                
                layer.msg(successMsg + skipMsg, {
                    icon: newRecords.length > 0 ? 1 : 0,
                    time: 2000
                });

            } catch (error) {
                layer.close(loadingIndex);
                if (error.name === 'QuotaExceededError') {
                    layer.msg('本地存储空间已满，请清理部分记录后重试', {
                        icon: 2,
                        time: 3000
                    });
                } else {
                    layer.msg('导入失败：' + error.message, {
                        icon: 2,
                        time: 2000
                    });
                }
            }
        });
    }
</script>
